package com.oss.service.impl;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.oss.client.dto.OssSecurityRequest;
import org.oss.client.dto.OssSecurityResponse;
import org.oss.client.dto.UrlRequest;
import org.oss.client.dto.UrlResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.CodingUtils;
import com.oss.base.BaseConst;
import com.oss.base.dao.IBaseDao;
import com.oss.service.ISecurityService;
import com.oss.service.IStorageService;
import com.oss.vo.OssFileInfo;
import com.oss.vo.SysUser;
@Service("storageService")
public class StorageService implements IStorageService{

	@Autowired
	IBaseDao baseDao;
	@Autowired
	ISecurityService securityService;
	
	@Override
	public String saveFileInfo(OssSecurityRequest req,SysUser user) {
		try {

			initDefault(user,req);
			
			OssFileInfo file = new OssFileInfo();
			file.setBucket(req.getBucket());
			file.setEndpoint(req.getEndpoint());
			file.setOrignalName(req.getFileName());
			file.setOssKey(req.getPath());
			file.setSize(req.getFileSize());
			baseDao.save(file);
			baseDao.flush();
			return file.getId();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		
	}
	
	/**
	 * 
	* Title: initDefault
	* Description: 对空值进行初始化,使用默认的配置值
	* @author   wjt
	* @date       2016-2-2
	* @param user
	* @param req
	 */
	private void initDefault(SysUser user, OssSecurityRequest req) {
		
		if(StringUtils.isEmpty(req.getBucket())){
			req.setBucket(user.getBucket());
		}
		
		if(StringUtils.isEmpty(req.getEndpoint())){
			req.setEndpoint(user.getEndpoint());
		}
		
		if(StringUtils.isEmpty(req.getPath())){
			SimpleDateFormat dft=new SimpleDateFormat("yyyyMMdd");    
			String date = dft.format(new Date());
			req.setPath(user.getAppPath()+date+"/");
		}
	}

	@Override
	public UrlResponse genFileUrl(UrlRequest req,OssSecurityResponse security,OssFileInfo file) {
		try {
			CodingUtils.assertParameterNotNull(security, "security info");
	    	String accessKeyId =security.getAccessKeyId();
			String accessKeySecret =  security.getAccessKeySecret();
			String securityToken =  security.getSecurityToken();
			String key = file.getOssKey()+file.getId()+"-"+file.getOrignalName();
			String endpoint = security.getEndpoint();
			String bucketName = security.getBucketName();
			OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret, securityToken);
			// 失效时间
			Date expiration = new Date(new Date().getTime() + 1800 * 1000);

			// URL
			URL url = client.generatePresignedUrl(bucketName, key, expiration);
			return buildSuccessRes(url);
		} catch (Exception e) {
			e.printStackTrace();
			return buildFailedRes(e);
		}
		
	}

	private UrlResponse buildFailedRes(Exception e) {
		UrlResponse res = new UrlResponse();
		res.setResultCode(BaseConst.RESPONSE_CODE_FAILED);
		res.setResultMsg(e.getMessage());
		return res;
	}


	private UrlResponse buildSuccessRes(URL url) {
		UrlResponse res = new UrlResponse();
		res.setResultCode(BaseConst.RESPONSE_CODE_SUCCESS);
		res.setUrlStr(url.toExternalForm());
		return res;
	}

	@Override
	public OssFileInfo getFileById(UrlRequest req) {

		OssFileInfo file = baseDao.get(OssFileInfo.class, req.getFileId());
		
		initDefault(file, req);
		
		return file;
	}

	/**
	 * 
	* Title: initDefault
	* Description: 对空值进行初始化,使用默认的配置值
	* @author   wjt
	* @date       2016-2-2
	* @param user
	* @param req
	 */
	private void initDefault(OssFileInfo user, UrlRequest req) {
		
		if(StringUtils.isEmpty(req.getBucket())){
			req.setBucket(user.getBucket());
		}
		
		if(StringUtils.isEmpty(req.getEndpoint())){
			req.setEndpoint(user.getEndpoint());
		}
		
		if(StringUtils.isEmpty(req.getPath())){
			req.setPath(user.getOssKey());
		}
	}
	
}
